package api

import (
	"gitcode.com/G-YT/iHealth25/server/global"
	"gitcode.com/G-YT/iHealth25/server/model/common/response"
	"gitcode.com/G-YT/iHealth25/server/plugin/weixin/model"

	//memberOrderReq "gitcode.com/G-YT/iHealth25/server/plugin/weixin/model/wxPay/request"
	"io"
	"net/http"

	"gitcode.com/G-YT/iHealth25/server/plugin/weixin/service"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	//"strconv"
)

type WxPayApi struct{}

// CreateJSApiOrder 创建会员订单【JSAPI】
func (p *WxPayApi) CreateJSApiOrder(c *gin.Context) {
	var req model.JSAPIPayRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage("参数错误: "+err.Error(), c)
		return
	}

	// 创建JSAPI支付订单
	orderResp, err := service.ServiceGroupApp.CreateJSAPIOrder(req)
	if err != nil {
		global.GVA_LOG.Error("创建JSAPI订单失败", zap.Error(err))
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.OkWithData(orderResp, c)
}

// PaymentNotify 微信支付回调处理
func (p *WxPayApi) PaymentNotify(c *gin.Context) {
	// 记录回调开始
	global.GVA_LOG.Info("收到微信支付回调请求",
		zap.String("remote_addr", c.ClientIP()),
		zap.String("user_agent", c.GetHeader("User-Agent")),
		zap.String("content_type", c.GetHeader("Content-Type")),
	)

	// 读取请求体
	body, err := io.ReadAll(c.Request.Body)
	if err != nil {
		global.GVA_LOG.Error("读取微信回调数据失败",
			zap.Error(err),
			zap.String("remote_addr", c.ClientIP()),
		)
		c.JSON(http.StatusBadRequest, gin.H{"code": "FAIL", "message": "读取数据失败"})
		return
	}

	// 验证请求体是否为空
	if len(body) == 0 {
		global.GVA_LOG.Error("微信回调请求体为空",
			zap.String("remote_addr", c.ClientIP()),
		)
		c.JSON(http.StatusBadRequest, gin.H{"code": "FAIL", "message": "请求体为空"})
		return
	}

	// 获取请求头信息用于验签
	headers := map[string]string{
		"Wechatpay-Signature": c.GetHeader("Wechatpay-Signature"),
		"Wechatpay-Timestamp": c.GetHeader("Wechatpay-Timestamp"),
		"Wechatpay-Nonce":     c.GetHeader("Wechatpay-Nonce"),
		"Wechatpay-Serial":    c.GetHeader("Wechatpay-Serial"),
	}

	// 验证必要的请求头是否存在
	for key, value := range headers {
		if value == "" {
			global.GVA_LOG.Error("微信回调缺少必要请求头",
				zap.String("missing_header", key),
				zap.String("remote_addr", c.ClientIP()),
			)
			c.JSON(http.StatusBadRequest, gin.H{"code": "FAIL", "message": "缺少必要请求头"})
			return
		}
	}

	// 记录回调详细信息（不包含敏感数据）
	global.GVA_LOG.Info("微信回调请求详情",
		zap.String("timestamp", headers["Wechatpay-Timestamp"]),
		zap.String("nonce", headers["Wechatpay-Nonce"]),
		zap.String("serial", headers["Wechatpay-Serial"]),
		zap.Int("body_length", len(body)),
	)

	// 处理支付回调
	err = service.ServiceGroupApp.HandlePaymentNotify(body, headers)
	if err != nil {
		global.GVA_LOG.Error("处理微信支付回调失败",
			zap.Error(err),
			zap.String("remote_addr", c.ClientIP()),
			zap.String("timestamp", headers["Wechatpay-Timestamp"]),
		)
		c.JSON(http.StatusBadRequest, gin.H{"code": "FAIL", "message": "处理失败"})
		return
	}

	// 记录处理成功
	global.GVA_LOG.Info("微信支付回调处理成功",
		zap.String("remote_addr", c.ClientIP()),
		zap.String("timestamp", headers["Wechatpay-Timestamp"]),
	)

	// 返回成功响应给微信
	c.JSON(http.StatusOK, gin.H{"code": "SUCCESS", "message": "成功"})
}
